using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Application.Contracts.Customized.RoomSourceVerifyV1.Dtos;
using SOEI.Solution.Customized.Dtos;
using SOEI.Solution.DomainEntities.RoomSourceVerifiy.Dtos;
using SOEI.Solution.DomainEntities.RoomSourceVerifiyV1.DomainService;
using SOEI.Solution.DomainEntities.RoomSourceVerifiyV1.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace SOEI.Solution.DomainEntities.RoomSourceVerifiyV1
{
    /// <summary>
    /// 【扩展模块】  <br/>
    /// 【功能描述】  ：XXX 模块<br/>
    /// 【创建日期】  ：2020.05.21 <br/>
    /// 【开发人员】  ：static残影<br/>
    ///</summary>
    [ApiExplorerSettings(GroupName = "Manager", IgnoreApi = false)]
    public class RoomVerifyV1AppService : SolutionAppServiceBase, IRoomVerifyV1AppService
    {
        /// <summary>
        ///【RoomVerifyV1】仓储层
        /// </summary>
        private readonly IRepository<RoomVerifyV1, string> _roomverifyv1Repository;

        /// <summary>
        ///【RoomVerifyV1】领域服务
        /// </summary>
        private readonly IRoomVerifyV1Manager _roomverifyv1Manager;


        /// <summary>
        ///【RoomVerifyV1】仓储层
        /// </summary>
        private readonly IRepository<LicensesUpload, string> _licensesuploadRepository;

        private readonly IRepository<CommissionContractDigest, string> _commissioncontractdigestRepository;

        //
        private readonly IRepository<CommissionContractMainBody, string> _commissionContractMainBodyRepository;

        public RoomVerifyV1AppService(
            IRepository<RoomVerifyV1, string> roomverifyv1Repository,
            IRoomVerifyV1Manager roomverifyv1Manager,
            IRepository<LicensesUpload, string> licensesuploadRepository,
            IRepository<CommissionContractDigest, string> commissioncontractdigestRepository,
            IRepository<CommissionContractMainBody, string> commissionContractMainBodyRepository
        )
        {
            _roomverifyv1Repository = roomverifyv1Repository;
            _roomverifyv1Manager = roomverifyv1Manager;
            _licensesuploadRepository = licensesuploadRepository;
            _commissioncontractdigestRepository = commissioncontractdigestRepository;
            _commissionContractMainBodyRepository = commissionContractMainBodyRepository;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        ///【RoomVerifyV1】获取的分页列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<PagedResultDto<RoomVerifyV1ListDto>> GetPaged(GetRoomVerifyV1sInput input)
        {
            var query = _roomverifyv1Repository.GetAll()
                          //模糊搜索 字段Id
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Id.Contains(input.FilterText));
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            var entityListDtos = ObjectMapper.Map<List<RoomVerifyV1ListDto>>(entityList);

            return new PagedResultDto<RoomVerifyV1ListDto>(count, entityListDtos);
        }

        /// <summary>
        ///【RoomVerifyV1】通过指定id获取MemberListDto信息
        /// </summary>
        [AbpAuthorize()]
        public async Task<RoomVerifyV1ListDto> GetById(EntityDto<string> input)
        {
            var entity = await _roomverifyv1Repository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<RoomVerifyV1ListDto>(entity);
            return dto;
        }

        /// <summary>
        ///【Company】 获取编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<GetRoomVerifyV1ForEditOutput> GetForEdit(EntityDto<string> input)
        {
            var output = new GetRoomVerifyV1ForEditOutput();
            RoomVerifyV1EditDto editDto;

            if (!string.IsNullOrEmpty(input.Id))
            {
                var entity = await _roomverifyv1Repository.GetAsync(input.Id);
                editDto = ObjectMapper.Map<RoomVerifyV1EditDto>(entity);
            }
            else
            {
                editDto = new RoomVerifyV1EditDto();
            }
            output.RoomVerifyV1 = editDto;
            return output;
        }
        /// <summary>
        ///【RoomVerifyV1】 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task CreateOrUpdate(CreateOrUpdateRoomVerifyV1Input input)
        {
            if (!string.IsNullOrEmpty(input.RoomVerifyV1.Id))
            {
                await Update(input.RoomVerifyV1);
            }
            else
            {
                await Create(input.RoomVerifyV1);
            }
        }
        /// <summary>
        ///【RoomVerifyV1】新增
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task<RoomVerifyV1EditDto> Create(RoomVerifyV1EditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<RoomVerifyV1>(input);
            //调用领域服务
            entity = await _roomverifyv1Manager.CreateAsync(entity);

            var dto = ObjectMapper.Map<RoomVerifyV1EditDto>(entity);
            return dto;
        }

        /// <summary>
        ///【RoomVerifyV1】编辑
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task Update(RoomVerifyV1EditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            var key = input.Id;
            var entity = await _roomverifyv1Repository.GetAsync(key);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _roomverifyv1Manager.UpdateAsync(entity);
        }

        /// <summary>
        ///【RoomVerifyV1】删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task Delete(EntityDto<string> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _roomverifyv1Manager.DeleteAsync(input.Id);
        }

        /// <summary>
        ///【RoomVerifyV1】 批量删除Member的方法
        /// </summary>
        [AbpAuthorize()]
        public async Task BatchDelete(List<string> input)
        {
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _roomverifyv1Manager.BatchDelete(input);
        }

        #endregion

        #region -------------------------------------------------用户自定义------------------------------------------------
        /*请在此扩展应用服务实现*/

        /// <summary>
        ///  检查输入的项目如：产权证号 是否可用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<GetVerifyCheckResultOutput> ForCheck(CheckVerifyInput input)
        {
            #region 废弃
            //var output = new GetVerifyCheckResultOutput();
            //// 1. 是否创建过产权信息
            //output.HasRoomVerify = await _roomverifyv1Manager.IsExistAsync(input.CQZH);
            //// 2.产权是否可以交易（需要验证）
            //output.IsTradable = true;
            //// 3.是否存在我的机构申请信息

            //// 4.成功了则返回
            //output.Checked = true; // 验证通过
            //output.Message = "当前产权允许交易，可以协助产权人进行资料提交！";

            //output.WZSQRXM = input.WZSQRXM;
            //output.WZSQRZJHM = input.WZSQRZJHM;
            //output.CQZH = input.CQZH;
            //output.HouseLocated = "陕西省西安市雁塔区xxx";
            //output.PropertyState = "正常";
            //return output;
            #endregion

            var output = new GetVerifyCheckResultOutput();

            var result = await _roomverifyv1Manager.ForCheck(input.SFBDC, input.CQZH, input.WZSQRZJLXDM, input.WZSQRZJHM, input.WZSQRXM);

            output.Message = result;

            return output;

        }

        /// <summary>
        ///【RoomVerifyV1】 快速核验保存
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// 
        [AbpAuthorize()]
        public async Task<FastVerifyV1EditDto> FastVerifySave(FastVerifyV1EditDto input)
        {
            var entity = ObjectMapper.Map<RoomVerifyV1>(input);

            string logicId = Guid.NewGuid().ToString("N");

            logicId = "A0" + logicId.Substring(logicId.Length - 8, logicId.Length - (logicId.Length - 8));

            entity.Id = logicId;

            entity.SJLY = "XMS";//XMS:新模式

            //调用领域服务
            entity = await _roomverifyv1Manager.CreateAsync(entity);

            var dto = ObjectMapper.Map<FastVerifyV1EditDto>(entity);

            return dto;

        }

        /// <summary>
        ///【RoomVerifyV1】 证照上传保存
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<List<LicensesUploadSaveEditDto>> LicensesUploadSave(List<LicensesUploadSaveEditDto> input)
        {
            var entitys = ObjectMapper.Map<List<LicensesUpload>>(input);

            foreach (var item in entitys)
            {
                string logicId = Guid.NewGuid().ToString("N");

                logicId = "A0" + logicId.Substring(logicId.Length - 8, logicId.Length - (logicId.Length - 8));

                item.Id = logicId;

                item.Id = await _licensesuploadRepository.InsertAndGetIdAsync(item);
            }

            var dto = ObjectMapper.Map<List<LicensesUploadSaveEditDto>>(entitys);

            return dto;

        }

        /// <summary>
		///【RoomVerifyV1】 委托协议【摘要】和【正文】保存
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize()]
        public async Task<CommissionContractInput> CommissionContractDigestAndMainBodySave(CommissionContractInput input)
        {
            var entity = ObjectMapper.Map<CommissionContractDigest>(input.DigestEditDto);

            string logicId = Guid.NewGuid().ToString("N");

            logicId = "A0" + logicId.Substring(logicId.Length - 8, logicId.Length - (logicId.Length - 8));

            entity.Id = logicId;

            entity.Id = await _commissioncontractdigestRepository.InsertAndGetIdAsync(entity);

            input.DigestEditDto = ObjectMapper.Map(entity, input.DigestEditDto);


            var entityMainBodys = ObjectMapper.Map<List<CommissionContractMainBody>>(input.MainBodyEditDtos);

            foreach (var item in entityMainBodys)
            {
                item.WTHTBH = "A0000000001";
                item.Id = await _commissionContractMainBodyRepository.InsertAndGetIdAsync(item);
            }

            input.MainBodyEditDtos = ObjectMapper.Map(entityMainBodys, input.MainBodyEditDtos);

            return input;

        }

        /// <summary>
		///【RoomVerifyV1】 通过指定合同编号获取合同内容
		/// </summary>
		/// <param name="ContractNum"></param>
		/// <returns></returns>
        [AbpAuthorize()]
        public async Task<List<MainBodyEditDto>> GetContractMainBodyByNum(string ContractNum)
        {
            var mainBodyEntitys = await _commissionContractMainBodyRepository.GetAll().Where(p => p.WTHTBH == ContractNum).ToListAsync();

            if (mainBodyEntitys != null)
            {
                var mainBodyDtos = ObjectMapper.Map<List<MainBodyEditDto>>(mainBodyEntitys);

                return mainBodyDtos;
            }

            return null;

        }

        /// <summary>
		///【RoomVerifyV1】 房源信息保存
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
        public async Task HousingInfoSave(HousingInfoEditDto input)
        {
            var entity = await _roomverifyv1Manager.FindByIdAsync(input.FBBH);

            if (entity != null)
            {
                var mapEntity = ObjectMapper.Map(input, entity);

                await _roomverifyv1Manager.UpdateAsync(mapEntity);
            }
        }

        #endregion
    }

}